import React, {Component} from 'react';
import {Button, Checkbox, DatePickerView, Flex, Picker, Radio, Slider, Toast, WhiteSpace} from 'antd-mobile';
// import {district} from 'antd-mobile-demo-data';
import HealthForm from './health-form';
import {district} from '../cityData';
import api from '../api/api';
import {util} from '../util/util';
import '../util/date.format';

const RadioItem = Radio.RadioItem;
const CheckboxItem = Checkbox.CheckboxItem;
const request = util.request();
const CityChildren = props => (
    <div
        onClick={props.onClick}
        style={{backgroundColor: '#fff', paddingLeft: 15}}
    >
        <div style={{textAlign: 'right', marginRight: 15}}>{props.extra}</div>
    </div>
);

class BaseInfoForm extends Component {
    state = {
        sexValue: '1',// 性别1：男 2：女
        ageValue: new Date().getFullYear() - (new Date('1995-01-01').getFullYear()),
        ageDateValue: new Date('1995-01-01'),
        heightValue: 180,
        weightValue: 70,
        professionData: [],
        professionValue: '',
        professionCode: '',
        cityData: [],
        pickerValue: ["110000", "110100", "110101"],// 城市默认选择值
        livingData: [],
        livingValue: '',
        workStatusData: [],
        eatingData: [],
        moreVisible: false,
        nextPage: false
    }

    componentDidMount() {
        let {professionData, eatingData, workStatusData} = this.state;
        // eatingData = ['暴饮暴食', '节食', '多荤少素', '喜爱甜食/碳酸/饮品/甜品', '盐重', '重口味(辛辣)', '零食代替正餐', '长期外卖'].map(item => ({
        //     "label": item,
        //     "value": item,
        //     "checked": false
        // }))
        // workStatusData = ['长期加班', '经常熬夜', '久坐', '长期出差', '朝九晚五', '退休', '全职主内'].map(item => ({
        //     "label": item,
        //     "value": item,
        //     "checked": false
        // }))

        // 职业数据请求
        this.requestProfession();
        // 城市数据请求
        this.requestCitys();
        // 更多 选项的数据
        // this.requestMore();

        this.setState({
            eatingData,
            workStatusData
        })

    }

    requestProfession = () => {
        let professionData = [];
        request.get(api.profession).then(response => {
            const {message} = response.data;
            if (message && message.length) {
                console.log(message)
                professionData = message.map(item => ({
                    ...item,
                    "label": item.name,
                    "value": item.value,
                    "checked": false
                }))
            }
            this.setState({
                professionData
            })
            //默认选中第一个职业
            professionData[0] && professionData[0].label && this.changeHandler('profession', professionData[0])
        }).catch(error => {
            console.log(error)
        })
    }
    requestCitys = () => {
        request.get(api.citys).then(response => {
            const {message} = response.data;
            if (message && message.length) {
                this.setState({
                    cityData: message
                })
            }
        }).catch(error => {
            console.log(error)
        })
    }
    //更多数据
    requestMore = () => {
        const {ageValue, sexValue, heightValue, weightValue, professionValue, professionCode, pickerValue, livingValue, workStatusData, eatingData} = this.state;
        let param = {
            age: parseInt(ageValue),
            sex: parseInt(sexValue),
            height: parseInt(heightValue),
            weight: parseInt(weightValue),
            occupation: professionCode,
            provinceCode: pickerValue[0],
            cityCode: pickerValue[1],
            areaCode: pickerValue[2]
        }

        request.post(api.advanced, {
            params: param
        }).then(response => {
            // console.log(response)
            const {data} = response;
            let {livingData, workStatusData, eatingData} = this.state;

            data.message.map(item => {
                let value = item.value;
                if (value === "life_state") {
                    livingData = item.itemList
                } else if (value === "work_state") {
                    workStatusData = item.itemList;
                } else if (value === "eating_habits") {
                    eatingData = item.itemList;
                }
            })


            this.setState({
                livingData,
                workStatusData,
                eatingData,
                moreData: data.message
            })
        })
    }
    // 改善状态 数据
    requestHealth = () => {
        const {ageValue, sexValue, heightValue, weightValue, professionValue, professionCode, pickerValue, livingValue, workStatusData, eatingData} = this.state;
        let param = {
            age: parseInt(ageValue),
            sex: parseInt(sexValue),
            height: parseInt(heightValue),
            weight: parseInt(weightValue),
            occupation: professionCode,
            provinceCode: pickerValue[0],
            cityCode: pickerValue[1],
            areaCode: pickerValue[2]
        }
        request.post(api.health, {
            params: param
        }, response => {
            console.log(response)
        });
    }

    changeHandler = (type, value, e) => {
        // console.log(type, value)
        // console.log(type, value, e)
        if (!type) return;
        switch (type) {
            case 'sex':
                this.setState({
                    sexValue: value
                }, () => {
                    this.requestMore();
                })
                break;
            case 'age': {
                let nowYear = new Date().getFullYear();
                let date = new Date(value);
                let year = date.getFullYear();
                this.setState({
                    ageValue: nowYear - year,
                    ageDateValue: date
                }, () => {
                    this.requestMore();
                })
                break;
            }
            case 'height':
                this.setState({
                    heightValue: value
                })
                break;
            case 'weight':
                this.setState({
                    weightValue: value
                })
                break;
            case 'heightCallback':
            case 'weightCallback':
                this.requestMore();
                break;
            case 'profession': {

                this.setState({
                    professionValue: value.label,
                    professionCode: value.value
                }, () => {
                    this.requestMore();
                })

                break;
            }
            case "living":
                this.setState({
                    livingValue: value.name,
                    livingCode: value.value
                })
                break;
            case 'workStatus': {
                const {workStatusData} = this.state;
                workStatusData.map(item => {
                    if (item.value === value.value) {
                        item.checked = e.target.checked
                    }
                })
                this.setState({
                    workStatusData
                })
                break;
            }
            case 'eating': {
                const {eatingData} = this.state;
                eatingData.map(item => {
                    if (item.value === value.value) {
                        item.checked = e.target.checked
                    }
                })
                this.setState({
                    eatingData
                })
                break;
            }
            default:
                break;
        }

    }
    clickHandler = (type, param, e) => {
        if (!type) return;
        switch (type) {
            case "more": {
                const {professionValue} = this.state;
                if (!professionValue) {
                    Toast.info('请选择职业', 1);
                    return false;
                } else {
                    this.setState({
                        moreVisible: !this.state.moreVisible
                    })
                }
                break;
            }
            case "next": {
                const {ageValue, sexValue, heightValue, weightValue, professionValue, professionCode, pickerValue, livingValue, workStatusData, eatingData} = this.state;
                if (!professionValue) {
                    Toast.info('请选择职业', 1);
                    return false;
                } else {
                    this.setState({
                        nextPage: true
                    })
                    this.requestHealth();
                }
                // Toast.info(`性别：${sexValue}；年龄：${ageValue}；身高：${heightValue}；体重：${weightValue}；职业：${professionCode}；城市：${pickerValue}；生活状态：${livingValue.toString()}；工作状态：${workStatusData}；饮食习惯：${eatingData}；`);

                break;
            }
            case "back": {
                this.setState({
                    nextPage: false
                })

            }
        }
    }

    renderProfession = () => {
        const {professionData, professionValue} = this.state;
        return professionData.map((item, index) => <RadioItem key={item.label} checked={professionValue === item.label}
                                                              onChange={this.changeHandler.bind(null, 'profession', item)}>
            <p className="p-icon"><img
                src={professionValue === item.label ? require(`../images/icon${index + 1}_a.png`) : require(`../images/icon${index + 1}.png`)}
                width="100%" alt=""/></p>
            <p>{item.label}</p>
        </RadioItem>)
    }
    renderLiving = () => {
        const {livingData, livingValue} = this.state;
        return livingData.map((item, index) => <RadioItem key={item.value} checked={livingValue === item.name}
                                                          className={livingValue === item.name ? 'active' : ''}
                                                          onChange={this.changeHandler.bind(null, 'living', item)}>
            <p>{item.name}</p>
        </RadioItem>)
    }
    renderWorkStatus = () => {
        const {workStatusData} = this.state;
        return workStatusData.map((item, index) => {
            // if (item.checked === undefined){
            //     item.checked = true;
            // }
            return <CheckboxItem className={item.checked ? 'active' : ''}
                                 checked={item.checked} key={item.value}
                                 onChange={(e) => this.changeHandler('workStatus', item, e)}>
                {item.name}
            </CheckboxItem>
        });
    }
    renderEating = () => {
        const {eatingData} = this.state;
        return eatingData.map((item, index) => <CheckboxItem className={item.checked ? 'active' : ''}
                                                             checked={item.checked} key={item.value}
                                                             onChange={(e) => this.changeHandler('eating', item, e)}>
            {item.name}
        </CheckboxItem>);
    }


    render() {
        const {nextPage, sexValue, ageValue, ageDateValue, heightValue, weightValue, professionValue, professionCode, cityData, pickerValue, moreVisible} = this.state;

        if (nextPage) {
            return (<HealthForm clickHandlerBack={this.clickHandler}/>)
        }
        return (
            <div className="base-info-form">
                <div className="fixed-top">
                    <a className="btn-back" href="javascript:history.back()"><i
                        className="icon anticon">&#xe620;</i></a>
                </div>
                <h2>选择您的基础信息</h2>
                <p>PiPi将为您定制专属的营养计划</p>

                <Flex>
                    <Flex.Item style={{flex: 1}}>
                        性别
                    </Flex.Item>
                    <Flex.Item style={{flex: 5}}>
                        <div className="sex-radios">
                            <RadioItem className={"man-radio " + (sexValue === '1' ? "active" : "")} key={1}
                                       checked={sexValue === '1'}
                                       onChange={this.changeHandler.bind(null, 'sex', '1')}><p className="p-icon"><i
                                className="icon anticon">&#xe6e2;</i></p>
                                <p>男</p>
                            </RadioItem>
                            <RadioItem className={"woman-radio " + (sexValue === '2' ? "active" : "")} key={2}
                                       checked={sexValue === '2'}
                                       onChange={this.changeHandler.bind(null, 'sex', '2')}><p className="p-icon"><i
                                className="icon anticon">&#xe6ec;</i></p>
                                <p>女</p>
                            </RadioItem>
                        </div>
                    </Flex.Item>
                </Flex>
                <WhiteSpace size="lg"/>
                <WhiteSpace size="lg"/>
                <Flex>
                    <Flex.Item style={{flex: 1}}>
                        年龄
                    </Flex.Item>
                    <Flex.Item style={{flex: 5}}>
                        <div className="show-value">
                            <span>{ageValue}</span>
                            <span>岁</span>
                        </div>
                    </Flex.Item>
                </Flex>
                <WhiteSpace size="lg"/>
                <Flex className="inset-shadow">
                    <Flex.Item>
                        <DatePickerView
                            value={ageDateValue}
                            onChange={this.changeHandler.bind(null, 'age')}
                            onValueChange={undefined}
                            mode="date"
                            minDate={new Date('1900-01-01')}
                        />
                    </Flex.Item>
                </Flex>
                <WhiteSpace size="lg"/>
                <WhiteSpace size="lg"/>
                <Flex>
                    <Flex.Item style={{flex: 1}}>
                        身高
                    </Flex.Item>
                    <Flex.Item style={{flex: 5}}>
                        <div className="show-value">
                            <span>{heightValue}</span>
                            <span>cm</span>
                        </div>
                    </Flex.Item>
                </Flex>
                <WhiteSpace size="lg"/>
                <Flex className="inset-shadow">
                    <Flex.Item>
                        <Slider
                            className="rule-slider"
                            style={{padding: '60px 0 30px', margin: '0 10px'}}
                            defaultValue={heightValue}
                            min={120}
                            max={240}
                            onChange={this.changeHandler.bind(null, 'height')}
                            onAfterChange={this.changeHandler.bind(null, 'heightCallback')}
                            marks={{
                                120: '120',
                                130: '130',
                                140: '140',
                                150: '150',
                                160: '160',
                                170: '170',
                                180: '180',
                                190: '190',
                                200: '200',
                                210: '210',
                                220: '220',
                                230: '230',
                                240: '240'
                            }}
                        />
                    </Flex.Item>
                </Flex>
                <WhiteSpace size="lg"/>
                <WhiteSpace size="lg"/>
                <Flex>
                    <Flex.Item style={{flex: 1}}>
                        体重
                    </Flex.Item>
                    <Flex.Item style={{flex: 5}}>
                        <div className="show-value">
                            <span>{weightValue}</span>
                            <span>kg</span>
                        </div>
                    </Flex.Item>
                </Flex>
                <WhiteSpace size="lg"/>
                <Flex className="inset-shadow">
                    <Flex.Item>
                        <Slider
                            className="rule-slider"
                            style={{padding: '60px 0 30px', margin: '0 10px'}}
                            defaultValue={weightValue}
                            min={30}
                            max={150}
                            onChange={this.changeHandler.bind(null, 'weight')}
                            onAfterChange={this.changeHandler.bind(null, 'weightCallback')}
                            marks={{
                                30: '30',
                                40: '40',
                                50: '50',
                                60: '60',
                                70: '70',
                                80: '80',
                                90: '90',
                                100: '100',
                                110: '110',
                                120: '120',
                                130: '130',
                                140: '140',
                                150: '150'
                            }}
                        />
                    </Flex.Item>
                </Flex>
                <WhiteSpace size="lg"/>
                <WhiteSpace size="lg"/>
                <Flex>
                    <Flex.Item style={{flex: 1}}>
                        职业
                    </Flex.Item>
                    <Flex.Item style={{flex: 5}}>
                        <div className="show-value">
                            <span>{professionValue}</span>
                        </div>
                    </Flex.Item>
                </Flex>
                <WhiteSpace size="lg"/>
                <Flex className="inset-shadow">
                    <Flex.Item>
                        <div className="profession-radios">
                            {this.renderProfession()}
                        </div>
                    </Flex.Item>
                </Flex>
                <WhiteSpace size="lg"/>
                <WhiteSpace size="lg"/>
                <Flex>
                    <Flex.Item style={{flex: 1}}>
                        城市
                    </Flex.Item>
                    <Flex.Item style={{flex: 5}}>
                        <Picker
                            title="选择地区"
                            extra="请选择(可选)"
                            // data={district}
                            data={cityData}
                            value={pickerValue}
                            onChange={v => this.setState({pickerValue: v})}
                            onOk={v => {
                                this.setState({pickerValue: v})
                            }}
                        >
                            <CityChildren/>
                        </Picker>
                    </Flex.Item>
                </Flex>

                <WhiteSpace size="lg"/>
                <WhiteSpace size="lg"/>
                <div className="more-info" onClick={this.clickHandler.bind(null, 'more')}>完善信息，营养计划更精准 <i
                    className="icon anticon">{moreVisible ? <span>&#xe61e;</span> : <span>&#xe61d;</span>}</i></div>
                <WhiteSpace size="lg"/>
                <div className={"more-info-layer" + (moreVisible ? 'show' : '')}>
                    <Flex>
                        <Flex.Item style={{color: "#000"}}>
                            我的生活状态
                        </Flex.Item>
                    </Flex>
                    <WhiteSpace size="lg"/>
                    <Flex>
                        <Flex.Item>
                            <div className="living-radios">
                                {this.renderLiving()}
                            </div>
                        </Flex.Item>
                    </Flex>
                    <WhiteSpace size="lg"/>
                    <WhiteSpace size="lg"/>
                    <Flex>
                        <Flex.Item style={{color: "#000"}}>
                            我的工作状态 <span style={{fontSize: '12px', color: '#999'}}>(可多选)</span>
                        </Flex.Item>
                    </Flex>
                    <WhiteSpace size="lg"/>
                    <Flex>
                        <Flex.Item>
                            <div className="work-checkboxs">
                                {this.renderWorkStatus()}
                            </div>
                        </Flex.Item>
                    </Flex>
                    <WhiteSpace size="lg"/><WhiteSpace size="lg"/>
                    <Flex>
                        <Flex.Item style={{color: "#000"}}>
                            我的饮食习惯 <span style={{fontSize: '12px', color: '#999'}}>(可多选)</span>
                        </Flex.Item>
                    </Flex>
                    <WhiteSpace size="lg"/>
                    <Flex>
                        <Flex.Item>
                            <div className="work-checkboxs">
                                {this.renderEating()}
                            </div>
                        </Flex.Item>
                    </Flex>
                    <WhiteSpace size="lg"/>
                    <WhiteSpace size="lg"/>
                </div>
                <Button className="pipi-btn" onClick={this.clickHandler.bind(null, 'next')}>下一步</Button>
                <WhiteSpace size="lg"/>
                <WhiteSpace size="lg"/>
            </div>
        )
    }
}

export default BaseInfoForm;